# coding=utf8
import sys
import json
import redis
import socket
import configparser

from settings import ENVIRON, FILENAME_CONFIG


FORMAT_PCONFIG = "{name}_{key}"


def get_host_type(host):
    if host in ["10.254.124.184", "192.168.241.1"]:  # 本地
        environ = "local"
    elif host in ["10.255.72.159", "10.255.72.90"]:  # Beta
        environ = "beta"
    elif host in ["10.10.204.16"]:  # 生产
        environ = "production"
    else:
        raise Exception("host, error. {0}".format(host))
    return environ


def write_config(servicehost=None, servicetype=ENVIRON):
    """
    初始化配置文件
    :return:
    """

    pconfig = {}

    config = configparser.ConfigParser()

    config["All"] = {
        "survival": 1,
        "proxy": 1,
        # "proxy_url": "http://10.10.203.136:8082/openapi/getProxyIP?type=uc",
    }

    config["SPIDER_CONFIG"] = pconfig

    configs = {
        # "proxy_url": {
        #     "section": "All",
        #     "local,beta": "http://10.10.203.136:8082/openapi/getProxyIP?type=uc",
        #     "production": "http://10.10.51.180:17301/openapi/getProxyIP?type=uc",
        # },
    }

    for key, configi in configs.items():
        for keyi in configi.keys():
            if servicetype in keyi:
                break
        else:
            raise Exception("变量没有找到，{0}，{1}".format(servicetype, key))

        if key == "rexample":
            for index, value in enumerate(configi[keyi]):
                config[configi["section"]][key + str(index + 1)] = value
        else:
            config[configi["section"]][key] = configi[keyi]

    fp = open(FILENAME_CONFIG, "w")
    config.write(fp)

    print("配置文件<{}>初始化成功。".format(FILENAME_CONFIG))


def _config(option, isint=False, israise=True, default=None):
    """
    获取配置文件某个Key的值
    :param option: 要获取Key
    :param isint: 是否返回int类型
    :return: 指定值，没有将报错
    """

    option = option.lower()

    config = configparser.ConfigParser()
    config.read(FILENAME_CONFIG)

    for sectioni in config.sections():
        if config.has_option(sectioni, option):
            if isint:
                return config.getint(sectioni, option)
            else:
                return config.get(sectioni, option)
    if israise and not default:
        raise Exception("not find option : {0} !".format(option))
    else:
        return default


def _config_section(section, israise=True):
    config = configparser.ConfigParser()
    config.read(FILENAME_CONFIG)

    if section in config.sections():
        return config.options(section)

    if israise:
        raise Exception("not find section : {0} !".format(section))
    else:
        return None


if __name__ == "__main__":
    write_config()
    print(_config("jdinfo_spider:DOWNLOAD_DELAY"))
